package py.com.fms.ven.session.maintenances;

//External classes imports 
//Java Classes
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports
import py.com.fms.fms.bean.EnterpriseBean;
import py.com.fms.fms.bean.PersonBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.persistence.services.EnterpriseServices;
import py.com.fms.fms.persistence.services.PersonServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.exception.CommonException;
import py.com.fms.session.ParamHolder;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.*;
import py.com.fms.ven.bean.CustomerBean;
import py.com.fms.ven.persistence.services.CustomerServices;

@SuppressWarnings("unused")
@Name("editCustomer")
@Scope(ScopeType.SESSION)
public class EditCustomer {
	
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{paramHolder}")
	private ParamHolder param;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In Credentials credentials;
	@In Identity identity;
	private UsersBean user;
	
	private DateAssistant dateAssist;

	// Attribute used for saving and deleting
	private CustomerBean customer;
	
	// Services
	private CustomerServices ctSrv;
	private PersonServices prSrv;
	private UsersServices usSrv;
	
	// Collection of monedasBean
	private Collection<CustomerBean> allCustomers;

	// Attribute used for editing or updating
	private CustomerBean editCustomer;
	
//	Necessary Attributes;
	private PersonBean personCod;
	private PersonBean personData;
	private Long personId;
	private Boolean canSave = false;



	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();
			this.loadParams();
			
			if(credentials != null){
				System.out.println("Credenciales Encontradas");
				this.getUser().setUserName(credentials.getUsername());
				System.out.println("User Name: " + this.getUser().getUserName());
				user = usSrv.getUserDataByName(this.getUser().getUserName());
				this.setUser(user);
				System.out.println("User: " + this.getUser());
			}else{	
				System.out.println("Credenciales Nulas");
			}
			
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	public void loadParams() throws CommonException{
		this.param.initData();
		this.param.loadParams();
	}
	
	public void initBeans(){
		
		if (customer == null){
			customer = new CustomerBean();
			customer.setStatus(true);
		}
		
		if (editCustomer == null){
			editCustomer = new CustomerBean();
		}
		if (personCod == null){
			personCod = new PersonBean();
		}
		if (personData == null){
			personData = new PersonBean();
		}
		
		if (user == null){
			user = new UsersBean();
		}
		
	}
	
	public void initServices() throws CommonException{
		
		if (sqlMap == null){
			sqlMap = new ServiceSqlMap();
		}
		
		if (ctSrv == null){
			ctSrv = new CustomerServices(this.sqlMap.getConfig());
		}
		
		if (prSrv == null){
			prSrv = new PersonServices(this.sqlMap.getConfig());
		}
		
		if (usSrv == null){
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		
				
	}
	
	public void initAssistants(){
		
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(param == null){
			param = new ParamHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
		
	}
	
	public void initCollections(){
		if(allCustomers == null){
			allCustomers = new ArrayList<CustomerBean>();
		}
		
	

	}
	
	public void cleanData(){

		customer = null;
		editCustomer = null;
		personCod = null;
		personData = null;
		user =  null;
		
		sqlMap = null;
		ctSrv = null;
		prSrv = null;
		usSrv = null;
		
		aid = null;
		param = null;
		convert = null;
		dateAssist = null;

		allCustomers = null;

	}

	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			this.setAllCustomers(ctSrv.getAllCustomers());
			for (CustomerBean customer : this.getAllCustomers()) {
				System.out.println(customer.getCod());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public String cancelData() throws CommonException {
//		this.facesMessages.clear();
		this.setInitVar("S");
		this.cleanData();
		this.initData();
		return null;
	}
		

	// Used for data saving process
	public void saveNewData() throws ParseException, CommonException {
		try {
//			this.facesMessages.clear();
			CustomerBean newCustomer = new CustomerBean();
			aid = new WithinHolder();
			this.today = DateAssistant.getHoleDateTime();
			personId = convert.getPersonId(this.getPersonCod());
			personData = convert.getPersonData(this.getPersonCod());
			
			if(this.getPersonId() == null){
				System.out.println("Person id is null");
			}else{
				System.out.println("Person id:" + this.getCustomer().getPersonData().getId());
			}		

			if (this.getCustomer() == null) {
				System.out.println("this.getCustomer() == null");
				throw new CommonException("error.fms.menu.error.countrynotexist");
			}
			System.out.println("ALL CLIENTS: " + this.getAllCustomers());
			if(this.getAllCustomers().isEmpty()){
				this.setCanSave(true);
			}else{
				for (CustomerBean customer : this.getAllCustomers()) {
					if(this.getCustomer().getPersonData().getId() == customer.getIdPerson()){
						FacesMessages.instance().add("Esta persona ya est� registrada como cliente");
						this.setCanSave(false);
						break;
					}else{
						this.setCanSave(true);
					}
					
				}
			}	
			System.out.println("Flag: " + this.getCanSave());
			if(this.getCanSave() == true){
				System.out.println("BEFORE SETTING VALUES");
				// Setting field values
				newCustomer.setCod(convert.convertField(this.getCustomer().getCod()));
				newCustomer.setIdPerson(this.getCustomer().getPersonData().getId());
				newCustomer.setIdEnt(param.getEnt().getId());
				newCustomer.setStatus(this.getCustomer().getStatus());
				newCustomer.setCreditLimit(this.getCustomer().getCreditLimit());
				newCustomer.setStartDate(this.today);
				newCustomer.setLastUpdDate(this.today);
				newCustomer.setLastPurchaseDate(this.today);
				System.out.println(this.today);
				newCustomer.setUserIns(user.getId());

				ctSrv.saveNewCustomer(newCustomer);
				
				// Initializing field values
				newCustomer = null;
				
				// Setting Initialization VAR
				this.setInitVar("S");
			}
			
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}finally{
			this.cleanData();
			this.setInitVar("S");
		}
	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id) throws CommonException{
		System.out.println("id = " + id.toString());
		for (CustomerBean bean : this.getAllCustomers()) {
			if(bean.getId() == id){
				this.setEditCustomer(bean);
				this.setPersonCod(convert.getPersonCod(bean.getIdPerson()));
				return;
			}			
		}	
	}
	
	public void dataToEditUpd() throws ParseException{
		try {
			// SETTING EXTERNAL VALUES
			personId = convert.getPersonId(this.getPersonCod());
			personData = convert.getPersonData(this.getPersonCod());
			
			// UPDATING EXTERNAL VALUES
			this.getEditCustomer().setIdPerson(this.getPersonId());
			
			// SAVING VALUES
			CustomerServices admSrv = new CustomerServices(this.sqlMap.getConfig());
			admSrv.updateCustomer(this.getEditCustomer());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void lastServUpd(CustomerBean bean) throws ParseException{
		try {
			this.initData();
			ServiceSqlMap map = new ServiceSqlMap();
			CustomerServices admSrv = new CustomerServices(map.getConfig());
			this.today = DateAssistant.getHoleDateTime();
			// UPDATING EXTERNAL VALUES
			this.setEditCustomer(bean);
			this.getEditCustomer().setLastUpdDate(today);
			this.getEditCustomer().setLastPurchaseDate(today);
			System.out.println("CLIENTE: " + bean.getId());

			// SAVING VALUES
			
			admSrv.updateCustomer(this.getEditCustomer());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void dataToDelete(Long id){
		for (CustomerBean bean: this.getAllCustomers()){
			if (bean.getId() == id) {
				try {
					CustomerServices admSrv  = new CustomerServices(this.sqlMap.getConfig());
					admSrv.deleteCustomerById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}

	// GETTERS AND SETTERS
	
	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public CustomerBean getCustomer() {
		return customer;
	}

	public void setCustomer(CustomerBean customer) {
		this.customer = customer;
	}

	public Collection<CustomerBean> getAllCustomers() {
		return allCustomers;
	}

	public void setAllCustomers(Collection<CustomerBean> allCustomers) {
		this.allCustomers = allCustomers;
	}

	public CustomerBean getEditCustomer() {
		return editCustomer;
	}

	public void setEditCustomer(CustomerBean editCustomer) {
		this.editCustomer = editCustomer;
	}

	public PersonBean getPersonCod() {
		return personCod;
	}

	public void setPersonCod(PersonBean personCod) {
		this.personCod = personCod;
	}

	public PersonBean getPersonData() {
		return personData;
	}

	public void setPersonData(PersonBean personData) {
		this.personData = personData;
	}

	public Long getPersonId() {
		return personId;
	}

	public void setPersonId(Long personId) {
		this.personId = personId;
	}

	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}
	
	public Boolean getCanSave() {
		return canSave;
	}

	public void setCanSave(Boolean canSave) {
		this.canSave = canSave;
	}

	
}
